<template>
  <div>
    <div style='max-width: 500px'>
      <q-form @submit.prevent.stop='onSubmit' @reset='onReset' class='q-gutter-md'>
        <div v-for='(item, index) in listArray' :key='index'>
          <q-select v-if='item.propertyType == "list0"' filled use-input v-model='item.value' :label='item.propertyName'
            :options='brandList' @update:model-value='selectBrand' @filter="filterBrandFn">
            <template v-slot:no-option>
              <q-item>
                <q-item-section class="text-grey">
                  No results
                </q-item-section>
              </q-item>
            </template>
          </q-select>
          <q-input v-if='item.propertyType == "list10"' filled disable :label='item.propertyName'
            v-model='item.value' />
          <q-select v-if='item.propertyType == "list11"' filled v-model="item.value" :label="item.propertyName"
            :options="carStoreNameList" style="width: 500px" @update:model-value='selectStoreName'>
          </q-select>

          <q-input v-if='item.propertyType == "list20"' filled disable :label='item.propertyName'
            v-model='item.value' />
          <q-select v-if='item.propertyType == "list21"' filled v-model="item.value" :label="item.propertyName"
            :options="carStoreNameList21" style="width: 500px" @update:model-value='selectStoreName21'>
          </q-select>

          <q-input v-if='item.propertyType == "list30"' filled disable :label='item.propertyName' />
          <q-select v-if='item.propertyType == "list31"' filled v-model="model" use-input input-debounce="0"
            :label="item.propertyName" :options="firstEntityArr" option-value="code" option-label="label"
            style="width: 500px">
          </q-select>

          <q-input v-if='item.propertyType == "list40"' filled disable :label='item.propertyName' />
          <q-select v-if='item.propertyType == "list41"' filled v-model="model" use-input input-debounce="0"
            :label="item.propertyName" :options="options" style="width: 500px">
          </q-select>

        </div>
        <div v-for='(item, index) in addCarArr' :key='index'>
          <q-input filled v-if='item.type == "date"' type="date" :hint='item.Rea_label' v-model='item.value' />

          <q-input v-if='item.type == "num"' filled type='number' v-model.number='item.value' :label='item.Rea_label' />

          <q-input v-if='item.type == "amt"' filled v-model="item.value" :label="item.Rea_label" mask="#.####"
            fill-mask="0" reverse-fill-mask />

          <q-input v-if='item.type == "char"' filled v-model='item.value' :label='item.Rea_label' />


          <div v-if='item.type == "treecode"'>
            <q-btn :label="item.Rea_label" color="secondary" @click="alert = true" />
            <q-dialog v-model="alert" full-width>
              <q-card style='height: 500px'>
                <q-card-section>
                  <TreeEntity :reqData='reqData' :tickType='mode' v-model:tickObj='ticked' @update:ticked='tickedFn' />
                </q-card-section>

                <q-card-actions align="right" class="bg-white text-teal">
                  <q-btn flat label="OK" v-close-popup />
                </q-card-actions>

              </q-card>
            </q-dialog>
          </div>
          <div v-if='item.type == "image"'>
            <div v-if="item['uploadFileStatus'] == 1" style="color: rgb(0,120,215);">正在上传文件</div>
            <div v-if="item['uploadFileStatus'] == 2" style="color: green">上传成功！</div>
            <div v-if="item['uploadFileStatus'] == 3" style="color: red">上传失败！</div>
            <q-uploader field-name='file' :label="item.Rea_label" multiple hide-upload-btn style="max-width: 300px"
              @click='touchFileUpload(item.label)' @added="uploadedFile($event, index)" />
          </div>

        </div>

        <div v-for='(item, index) in dicArray' :key='index'>
          <div @click='searchDic(item)'>
            <q-select ref='fix' filled v-model="item.value" :label="item.Rea_label" use-input input-debounce="0"
              :options="dicOptions" style="width: 500px" @update:model-value='getNumber(item, index)'>
              <template v-slot:no-option>
                <q-item>
                  <q-item-section class="text-grey">
                    No results
                  </q-item-section>
                </q-item>
              </template>
            </q-select>
          </div>
        </div>

        <div v-if='childCode == "01113"'>
          <q-btn label="点击查看品牌树" color="secondary" @click="alert = true" />
          <q-dialog v-model="alert" full-width>
            <q-card style='height: 500px'>
              <q-card-section>
                <TreeEntity v-if='brandFlag == true' :reqData='reqBrandData' :tickType='mode'
                  v-model:tickObj='tickedBrand' @update:ticked='tickedBrandFn' />
              </q-card-section>

              <q-card-actions align="right" class="bg-white text-teal">
                <q-btn flat label="OK" v-close-popup @click='getBrandCode' />
              </q-card-actions>

            </q-card>
          </q-dialog>
        </div>
        <div>
          <q-btn label='添加' type='submit' color='primary' />
          <q-btn label='重置' type='reset' color='primary' flat class='q-ml-sm' />
          <!--          <button type='button' @click='getSystemCode()'>测试</button>-->
        </div>
      </q-form>
    </div>
  </div>
</template>
<script lang='ts'>
import { useRouter, useRoute } from 'vue-router'
import { onMounted, onBeforeUnmount, ref, reactive, defineComponent } from 'vue'
import { postRequest, getRequest } from 'src/components/functions'
import { TableValue, columnSelection } from 'components/models'
import { useQuasar, Notify } from 'quasar'
import { useStore } from 'src/store'
import { api } from 'boot/axios'
import TreeEntity from '../tree/TreeEntity.vue'
import { ChanReqData } from 'pages/tree/model/Interfaces'
import { CarMessage } from 'src/store/sphinx/state';

let tempBrandList = []
export default defineComponent({
  name: 'Add.vue',
  components: { TreeEntity },
  computed: {
    serverURL() {
      return process.env.api
    }
  },
  setup(props, { emit }) {
    let brandFlag = ref(false)
    let alert = ref(false)
    let mode = ref('strict')
    let reqData = ref<ChanReqData>({
      "entityCode": "",
      "entityType": "",
      "length": "",
      "isRoot": "",
      "chainHead": "",
      "entityNo": ""
    })
    let reqBrandData = ref<ChanReqData>({
      "entityCode": "",
      "entityType": "",
      "length": "",
      "isRoot": "",
      "chainHead": "",
      "entityNo": ""
    })
    let tickedBrand = ref([])
    let ticked = ref([])
    let selections = ref(null)
    const model = ref([])
    let router = useRouter();
    let rote = useRoute();
    const store = useStore();
    const userData = store.state.sphinx.userData;
    const ChainData = store.state.sphinx.Chain;
    let preEntityData = []
    preEntityData = store.state.sphinx.selectedItemData;


    let addCarArr = ref<TableValue[] | undefined>();
    let totalColumns: any = []
    let entityCode = ref<any>('');
    let childCode = ref<any>('');
    let addDataUrl = ref('');
    const $q = useQuasar();
    let loadingTimer;
    let QueryBarUrl = ref<string>('');
    let operateEvent = ref(rote.query.operateEvent);
    let times = ref(0);
    let equ = ref('');
    let change = ref(true);
    let indexTemp
    let fix = ref()
    let entity = ref('')
    let otherEntity = ref('')
    let entityChild = ref('')
    let otherEntityChild = ref('')
    let imageControlItem = ''
    // 点击获取主体属性列表框
    function mouseover(item, fun) {
      let getListInterface = 'channel/channel/getPropertyInterface';
      //获取主体属性list的接口
      let resData = {
        entityCode: entityCode.value,
        entityType: childCode.value,
        eventCode: operateEvent.value,
        propertyCode: item.propertyCode
      };
      postRequest(getListInterface, resData, res => {
        let n = []
        if (res.data !== null && res.data.interfaceEnglish !== undefined) {
          QueryBarUrl.value = res.data.interfaceEnglish;
          if (res.status == 'SUCCESS') {
            postRequest(QueryBarUrl.value, '', (res) => {
              for (let i = 0; i < res.length; i++) {
                let e = item.propertyCode;
                n.push(res[i][e]);
              }
              fun(n, res, item.propertyCode);
            });
          }
        }
      });
    }

    //获取数据字典
    let stringOptions
    let dicOptions = ref([])
    function searchDic(item) {
      stringOptions = []
      let reqData = {
        entityCode: entityCode.value,
        entityType: childCode.value,
        propertyEnglish: item.label
      }
      getRequest('/channel/channel/queryEntityPropertyDic', (res) => {
        res.forEach((item, index, array) => {
          stringOptions.push(item.dicName)
        })

        if (dicOptions.value.length === 0) {
          if (fix?.value?.hidePopup) {
            fix?.value?.hidePopup()
            setTimeout(() => {
              fix?.value?.showPopup()

            }, 100)
          }

        }
        dicOptions.value = stringOptions
      }, reqData)
    }



    //获取属性名
    function getAddClomn() {
      let sceneCode = ''
      let requestSceneBody = [
        {
          "entityCode": '101',
          "codeName": '',
          "entityType": '01',
          "typeName": '',
          "eventCode": null,
          "eventName": null,
          "propertyEnglish": null,
          "propertyChinese": null,
          "propertyValue": null,
          "propertyCondition": null,
          "companyId": userData.companyId
        },
        {
          "entityCode": '102',
          "codeName": '',
          "entityType": '02',
          "typeName": '',
          "eventCode": null,
          "eventName": null,
          "propertyEnglish": 'roleType',
          "propertyChinese": null,
          "propertyValue": userData.roleType,
          "propertyCondition": null,
          "companyId": userData.companyId
        }];
      api.post('/channel/channel/getSceneCode', requestSceneBody).then(res => {
        if (res.status == 200) {
          sceneCode = res.data.data
          let url = 'channel/channel/instre';
          let postData = {
            entityCode: entityCode.value,
            entityType: childCode.value,
            sceneCode: sceneCode,
            objectCodeType: '002',
            companyId: userData.companyId
          };
          postRequest(url, postData, callback);
        }
      })
    }


    let dicArray = reactive([])
    let listArray = reactive([])
    function callback(data: any[]) {

      //老向开始
      let selectedItemDatum = store.state.sphinx.selectedItemData[store.state.sphinx.selectedItemData.length - 1];
      let item: any = {};
      let tempLate: any = {};
      let value1 = '';
      console.log('xpa selectedItemDatum', selectedItemDatum)
      if (selectedItemDatum !== undefined) {
        let s = JSON.stringify(selectedItemDatum);
        let swap = JSON.parse(s)
        //获取跳转过来的实体参数
        let prevOptEntity = store.state.sphinx.prevOptEntity;
        console.log('跳转前的主体记录swap', swap)
        console.log('获取跳转过来的实体参数prevOptEntity', prevOptEntity)
        console.log('请求地址', "/transaction/sub/fetchChannelRoute?relationFlag=5&entityCode=" + prevOptEntity.entityCode + "&entityType=" + prevOptEntity.childCode + "&otherEntityCode=" + entityCode.value + "&otherEntityType=" + childCode.value + "&otherEventCode=002")
        api.get(
          "/transaction/sub/fetchChannelRoute?relationFlag=5&entityCode=" + prevOptEntity.entityCode + "&entityType=" + prevOptEntity.childCode + "&otherEntityCode=" + entityCode.value + "&otherEntityType=" + childCode.value + "&otherEventCode=002"

        ).then(data1 => {
          tempLate = { entityCode: entityCode.value, entityType: childCode.value }
          //匹配路由参数
          for (let itm in swap) {
            data1.data.data.forEach(x => {
              if (x.propertyEnglish === itm) {
                tempLate[x.otherPropertyEnglish] = swap[itm]
              }
            })
          }

          //匹配到的参数
          console.log('跳转映射匹配到的参数', tempLate)

          //老向结束


          totalColumns = data;
          console.log('totalColumns:', totalColumns)
          let n: TableValue[] = [];
          if (data) {
            data.forEach((item, index, array) => {

              if (item.propertyType === "list11") {
                getSelectList(item.propertyCode)
              }
              if (item.propertyType === "list21") {
                getSelectList21(item.propertyCode)
              }
              if (item.propertyType === "list0") {
                getBrandList(item.propertyCode);
              }
            })
            data.forEach((item) => {
              if (item.propertyType.indexOf('list') != -1) {
                listArray.push({
                  "propertyCode": item.propertyCode,
                  "propertyName": item.propertyName,
                  "propertyType": item.propertyType,
                  "value": ""
                })
              } else if (item.propertyType == "dic") {
                dicArray.push({
                  Rea_label: item.propertyName,
                  value: '',
                  label: item.propertyCode,
                  code: '',
                  length: item.propertyLength,
                  type: item.propertyType,
                })
              } else {

                console.log("最后逻辑")

                //跳转映射匹配到的参数 tempLate,如果item.propertyCode与tempLate的itm相等饿时候，取tempLate的值

                for (let itm in tempLate) {

                  // console.log("外面value1:",value1)
                  // console.log("外面itm:",itm)
                  // console.log("外面item.propertyCode:",item.propertyCode)

                  if (item.propertyCode === itm) {
                    value1 = tempLate[itm];
                    console.log("value1 =tempLate[itm]:", value1)
                    console.log("itm:", itm)
                    console.log("item.propertyCode:", item.propertyCode)
                  }

                }


                n.push(
                  {
                    Rea_label: item.propertyName,
                    value: value1,
                    label: item.propertyCode,
                    length: item.propertyLength,
                    type: item.propertyType,
                    time: false,
                    arr: [],
                    arrTemp: [],
                    selected: "",
                    selectionsData: null,
                    item: undefined
                  }
                )
                value1 = '';
              }
            });
          }
          addCarArr.value = n;



        })
      }

      //selectedItemDatum为undefined时，说明该主体直接增加，走以前逻辑不是基于关系如配料的增加
      if (selectedItemDatum === undefined) {
        totalColumns = data;
        console.log('totalColumns:', totalColumns)
        let n: TableValue[] = [];
        if (data) {
          data.forEach((item, index, array) => {
            if (item.propertyType === "list11") {
              getSelectList(item.propertyCode)
            }
            if (item.propertyType === "list21") {
              getSelectList21(item.propertyCode)
            }

            if (item.propertyType === "list0") {
              getBrandList(item.propertyCode);
            }
          })
          data.forEach((item) => {
            if (item.propertyType.indexOf('list') != -1) {
              listArray.push({
                "propertyCode": item.propertyCode,
                "propertyName": item.propertyName,
                "propertyType": item.propertyType,
                "value": ""
              })
            } else if (item.propertyType == "dic") {
              dicArray.push({
                Rea_label: item.propertyName,
                value: '',
                label: item.propertyCode,
                code: '',
                length: item.propertyLength,
                type: item.propertyType,
              })
            } else {

              console.log("最后逻辑")

              //跳转映射匹配到的参数 tempLate,如果item.propertyCode与tempLate的itm相等饿时候，取tempLate的值

              for (let itm in tempLate) {

                console.log("外面value1:", value1)
                console.log("外面itm:", itm)
                console.log("外面item.propertyCode:", item.propertyCode)

                if (item.propertyCode === itm) {
                  value1 = tempLate[itm];
                  console.log("value1:", value1)
                  console.log("itm:", itm)
                  console.log("item.propertyCode:", item.propertyCode)
                }

              }


              n.push(
                {
                  Rea_label: item.propertyName,
                  value: value1,
                  label: item.propertyCode,
                  length: item.propertyLength,
                  type: item.propertyType,
                  time: false,
                  arr: [],
                  arrTemp: [],
                  selected: "",
                  selectionsData: null,
                  item: undefined
                }
              )
            }
          });
        }
        addCarArr.value = n;
        console.log('@@@@', addCarArr.value);
      }
    }

    function complieSelections(selectItems: string[], item: any, propertyCode: string): columnSelection[] {
      let selection: columnSelection[] = []

      selectItems.forEach((x: any) => {
        const selectItem: columnSelection = { label: x[propertyCode], value: x[propertyCode], item: item, selections: x.companyType }
        selection.push(selectItem)
      })
      return selection;
    }

    function getPropertysByPropertyType(propertyType: string): any {
      let propertyCode = undefined
      const s = propertyType.substring(0, propertyType.length - 1) + "0";
      totalColumns.forEach((x: any) => {
        if (x.propertyType == s) {
          if (propertyCode === undefined) {
            propertyCode = x.propertyCode
          }
        }
      })
      return propertyCode
    }

    function getIndexByPropertyCode(propertyCode: string, companyType: string) {
      const value = addCarArr.value;
      value.forEach((x: any, y: number) => {
        if (x.label == propertyCode) {
          if (x.item !== undefined) {
            x.item.forEach((z: any) => {
              const itemElement = z[propertyCode];
              if (itemElement !== undefined && itemElement == companyType) {
                x.value = { label: itemElement, value: itemElement, item: z }
              }
            })
          }
        }
      })
      addCarArr.value = value;
    }


    function getAdddataUrl() {
      let data = {
        entityCode: entityCode.value,
        entityType: childCode.value,
        theirEventCode: '002'
      };
      postRequest('/channel/channel/getInterface', data, res => {
        let url = res.data.interfaceEnglish;
        addDataUrl.value = url.substr(url.indexOf('/') + 1)
      });
    }

    //通过选取的树节点获取对应的系统代码
    function getSystemCode() {
      let reqCodeData = []
      ticked.value.forEach((item, index, array) => {
        const { id, chainTail, chainHead, codeName, entityCode, entityType, typeName, entityNo, propertyCodeName } = item.relationNode
        console.log("item.relationNode-add", item.relationNode);

        reqCodeData.push({
          "id": id,
          "chainHead": chainHead,
          "entityCode": entityCode,
          "codeName": codeName,
          "entityType": entityType,
          "typeName": typeName,
          "entityNo": entityNo,
          "entityNoName": propertyCodeName,
          "companyId": userData.companyId,
          "companyName": userData.companyName,
          "chainTail": chainTail
        })
      })
      postRequest('/route/route/insertNoTree', reqCodeData, res => {
        addCarArr.value.forEach((item, index, array) => {
          if (item.label == "systemCode") {
            item.value = res;
          }
        })
      })
    }
    //通过选择的树节点获取相应的品牌代码
    function getBrandCode() {
      let reqCodeData = []
      tickedBrand.value.forEach((item, index, array) => {
        const { id, chainTail, chainHead, codeName, entityCode, entityType, typeName, entityNo, propertyCode, propertyCodeName, codeValue } = item.relationNode
        reqCodeData.push({
          "id": id,
          "chainHead": chainHead,
          "entityCode": entityCode,
          "codeName": codeName,
          "entityType": entityType,
          "typeName": typeName,
          "entityNo": entityNo,
          "entityNoName": propertyCodeName,
          "companyId": userData.companyId,
          "companyName": userData.companyName,
          "chainTail": chainTail,
          "propertyEnglish": propertyCode,
          "propertyChinese": propertyCodeName,
          "propertyValue": codeValue,
          "propertyCondition": null,
        })
      })
      postRequest('/route/route/insertNoTree', reqCodeData, res => {
        addCarArr.value.forEach((item, index, array) => {
          if (item.label == "carTypeTree") {
            item.value = res;
          }
        })
      })
    }

    function onSubmit() {
      console.log("submit，entityCode=", entityCode.value);
      console.log("submit，childCode=", childCode.value);
      //  getSystemCode();   老向注释
      console.log("添加添加");
      setTimeout(() => {
        let data = {
          entityCode: entityCode.value,
          entityType: childCode.value,
          companyId: userData.companyId,
          scene: ChainData
        };
        console.log("添加1，data=", data);
        data = Object.assign(data, store.state.sphinx.selectedItemData[store.state.sphinx.selectedItemData.length - 1]);
        console.log("添加2，data=", data);

        console.log("添加2，addCarArr=", addCarArr);

        if (addCarArr.value !== undefined) {
          for (let i = 0; i < addCarArr.value.length; i++) {
            let key = addCarArr.value[i].label;
            let val: any
            if (typeof (addCarArr.value[i].value) !== 'object') {
              val = addCarArr.value[i].value;
              data[key] = val;
            } else {
              let obj: any = addCarArr.value[i].value;
              if (addCarArr.value[i].type == 'image') {
                data[key] = JSON.parse(JSON.stringify(obj))
              } else if (obj.hasOwnProperty('value')) {
                val = obj.value
                data[key] = val;
              }

            }
          }
        }
        console.log("添加3，data=", data);
        /**********************************/
        dicArray.forEach((item, index, array) => {
          data[item.label] = item.code
        })

        console.log("添加4，data=", data);
        listArray.forEach((item, index, array) => {
          data[item.propertyCode] = item.value
        })

        //添加images
        for (let i = 0; i < Object.keys(preToAddImages).length; i++) {
          data[Object.keys(preToAddImages)[i]] = preToAddImages[Object.keys(preToAddImages)[i]]
        }

        //因前面逻辑有问题，强制赋值当前主体的entityCode、childCode数据  老向
        data.entityCode = entityCode.value;
        data.entityType = childCode.value;

        console.log("添加9，postRequest data=", data);
        postRequest(addDataUrl.value, data, (res) => {
          if (res) {
            emit('rightInfo', {
              opName: 'refreshRight'
            })
            $q.loading.show({
              message: res
            });
            loadingTimer = setTimeout(() => {
              $q.loading.hide();
              loadingTimer = void 0;
              void router.go(-1);
            }, 1000);
          }
        });
      }, 1000)
    }
    function filterFn(val, update, abort) {
      setTimeout(() => {
        const tableValue = addCarArr.value[indexTemp];
        const arrTemp = tableValue.arrTemp;
        update(() => {
          const needle = val.toLocaleLowerCase()
          tableValue.arr = arrTemp.filter(v => v.label.toLocaleLowerCase().indexOf(needle) > -1)

        })
      }, 300)
    }

    function touch(index) {
      indexTemp = index;
    }
    function setModel(val) {
      const propertysByPropertyType = getPropertysByPropertyType(val.item.propertyType);
      getIndexByPropertyCode(propertysByPropertyType, val.selections);
      model.value = val
    }

    onBeforeUnmount(() => {
      if (loadingTimer !== void 0) {
        clearTimeout(loadingTimer);
        $q.loading.hide();
      }
    });

    function yeso(item) {
      if (item.substring(0, 4) == 'list') {
        return true
      } else {
        return false
      }
    }

    function onReset() {
      debugger
      for (let i = 0; i < addCarArr.value.length; i++) {
        addCarArr.value[i].value = '';
      }
    }
    function getNumber(item, index) {
      let reqData = {
        entityCode: entityCode.value,
        entityType: childCode.value,
        propertyEnglish: item.label
      }
      getRequest('/channel/channel/queryEntityPropertyDic', (res) => {
        res.forEach((i, index1, array) => {
          if (i.dicName == item.value) {
            dicArray[index].code = i.dicCode;
          }
        })
        // console.log(dicArray);
      }, reqData)
    }

    //获取一级主体数据
    let firstEntityArr = reactive([])
    function getFirstEntity() {
      getRequest('/channel/channel/queryFirstEntity', res => {
        res.forEach((item, index, array) => {
          firstEntityArr.push({
            label: item.codeName,
            code: item.entityCode,
            value: ''
          })
        })
        // console.log(firstEntityArr);
      }, { "companyId": userData.companyId })
    }

    /**
     * 获取选项下拉菜单列表
     */
    let propertyCodeTemp = ref('')
    let propertyCodeTemp1 = ref('')
    let propertyCodeTemp2 = ref('')
    let carStoreNameList = reactive([])
    let carStoreNameList21 = reactive([])
    let carTempList = reactive([])
    let carTempList21 = reactive([])
    let toEntityCode, toEntityType;
    let toEntityCode21, toEntityType21;

    function getSelectList(propertyCode) {
      console.log(propertyCode);//roleName
      propertyCodeTemp.value = propertyCode
      console.log(propertyCodeTemp.value);//roleName
      const reqData = {
        "companyId": userData.companyId,
        "entityCode": entityCode.value,
        "entityType": childCode.value,
        "eventCode": operateEvent.value,
        "propertyCode": propertyCode
      }
      postRequest('channel/channel/getPropertyInterface', reqData, res => {
        if (res.status == "SUCCESS") {
          let getListUrl = res.data.interfaceEnglish;
          let reqData = Object.assign({ "companyId": userData.companyId }, store.state.sphinx.selectedItemData[store.state.sphinx.selectedItemData.length - 1]);

          console.log("getListUrl", getListUrl);
          let urls = getListUrl.substring(getListUrl.indexOf('/'), getListUrl.length);

          let strings1 = urls.split('?')[1].split('&');
          console.log("strings1:", strings1);
          //  let toEntityCode,toEntityType;
          strings1.forEach(x => {
            let strings = x.split('=');
            if (strings[0] === 'entityCode') {
              toEntityCode = strings[1]
            } else if (strings[0] === 'entityType') {
              toEntityType = strings[1]
            }
          })

          console.log("toEntityCode:", toEntityCode);
          console.log("toEntityType:", toEntityType);

          //老向开始
          console.log("老向开始")
          let url = res.data.interfaceEnglish;
          let requestType = url.substr(0, url.indexOf('/'));
          let formUrl = url.substr(url.indexOf('/') + 1);

          console.log("url", url);
          console.log("requestType", requestType);
          console.log("formUrl", formUrl);

          if (requestType.indexOf('get') !== -1) {
            getRequest(formUrl, analyzeCallback);
          } else {
            postRequest(formUrl, { companyId: userData.companyId }, analyzeCallback);
          }

          function analyzeCallback(res) {
            carTempList = res;
            console.log("list查询req：", res)
            console.log("propertyCode：", propertyCode)
            console.log("strings1[1]：", strings1[1])
            let ListCode = 'field5';
            let listName = 'field6';
            let url = "/transaction/sub/getEntityPropertyList?" + strings1[0] + "&" + strings1[1];

            console.log('preEntityData:', preEntityData)

            //增加映射条件的动态组织

            let reqUrl = "/transaction/sub/fetchChannelRoute?relationFlag=3&entityCode=" + entityCode.value + "&entityType=" + childCode.value + "&otherEventCode=002" + "&otherEntityCode=" + toEntityCode + "&otherEntityType=" + toEntityType;

            console.log('reqUrl:', reqUrl)

            getRequest(reqUrl, (resInDatas) => {
              resInDatas.forEach(x => {
                // x.propertyEnglish应该是otherpropertyEnglish?
                console.log('resInDatas:', x)
                console.log('resInDatas2:', x.propertyEnglish);
                let preEntityDatum = preEntityData[0];
                url += '&' + x.otherPropertyEnglish + '=' + preEntityDatum[x.propertyEnglish];
              })
              console.log('list下拉框请求地址', url);



              //   getRequest("/transaction/sub/getEntityPropertyList?"+strings1[1],(propertyListData) => {
              getRequest(url, (propertyListData) => {
                listName = propertyListData[0].listName;
                ListCode = propertyListData[0].listCode;
                console.log('listName', listName)
                console.log('ListCode', ListCode)
                propertyCodeTemp2.value = listName;
                propertyCodeTemp1.value = ListCode;

                res.forEach((item, index, array) => {

                  carStoreNameList.push(item[listName]);

                })
                console.log('carStoreNameList:', carStoreNameList)

              })
            })
          }
        }

        //老向结束


        //老向注释

        // postRequest(getListUrl,reqData,res=>{
        //   carTempList = res;
        //   res.forEach((item,index,array)=>{
        //     carStoreNameList.push(item[propertyCode])
        //   })
        // })

      })
    }


    //list21下拉框获取
    function getSelectList21(propertyCode) {
      console.log(propertyCode);//roleName
      propertyCodeTemp.value = propertyCode
      console.log(propertyCodeTemp.value);//roleName
      const reqData = {
        "companyId": userData.companyId,
        "entityCode": entityCode.value,
        "entityType": childCode.value,
        "eventCode": operateEvent.value,
        "propertyCode": propertyCode
      }
      postRequest('channel/channel/getPropertyInterface', reqData, res => {
        if (res.status == "SUCCESS") {
          let getListUrl = res.data.interfaceEnglish;
          let reqData = Object.assign({ "companyId": userData.companyId }, store.state.sphinx.selectedItemData[store.state.sphinx.selectedItemData.length - 1]);

          let urls = getListUrl.substring(getListUrl.indexOf('/'), getListUrl.length);

          let strings1 = urls.split('?')[1].split('&');
          console.log("strings1:", strings1);
          //  let toEntityCode,toEntityType;
          strings1.forEach(x => {
            let strings = x.split('=');
            if (strings[0] === 'entityCode') {
              toEntityCode21 = strings[1]
            } else if (strings[0] === 'entityType') {
              toEntityType21 = strings[1]
            }
          })

          console.log("toEntityCode21:", toEntityCode21);
          console.log("toEntityType21:", toEntityType21);

          //老向开始
          console.log("老向开始")
          let url = res.data.interfaceEnglish;
          let requestType = url.substr(0, url.indexOf('/'));
          let formUrl = url.substr(url.indexOf('/') + 1);

          console.log("url", url);
          console.log("requestType", requestType);
          console.log("formUrl", formUrl);

          if (requestType.indexOf('get') !== -1) {
            getRequest(formUrl, analyzeCallback);
          } else {
            postRequest(formUrl, { companyId: userData.companyId }, analyzeCallback);
          }

          function analyzeCallback(res) {
            carTempList21 = res;
            console.log("list查询req：", res)
            console.log("propertyCode：", propertyCode)
            let ListCode = 'field5';
            let listName = 'field6';

            //增加映射条件的动态组织

            let url = "/transaction/sub/getEntityPropertyList?" + strings1[0] + "&" + strings1[1];
            getRequest(url, (propertyListData) => {
              listName = propertyListData[0].listName;
              ListCode = propertyListData[0].listCode;
              console.log('listName', listName)
              console.log('ListCode', ListCode)
              propertyCodeTemp2.value = listName;
              propertyCodeTemp1.value = ListCode;

              res.forEach((item, index, array) => {

                carStoreNameList21.push(item[listName]);

              })
              console.log('carStoreNameList21:', carStoreNameList21)
            })

          }

          //老向结束


          //老向注释

          // postRequest(getListUrl,reqData,res=>{
          //   carTempList = res;
          //   res.forEach((item,index,array)=>{
          //     carStoreNameList.push(item[propertyCode])
          //   })
          // })
        }
      })
    }



    /**
     * 选择名称从而拿到值
     */
    function selectStoreName(value) {
      console.log(value);
      console.log('listArray:', listArray);
      console.log('carTempList:', carTempList);  //list对象的所有值
      console.log('开始addCarArr:', addCarArr);

      let properType = ''
      listArray.forEach((item, index, array) => {

        if (item.propertyType === "list10") {
          properType = item.propertyCode;
        }
      })

      properType = propertyCodeTemp1.value;
      console.log('properType:', properType);//roleType

      let tempValue = ''
      carTempList.forEach((item, index, array) => {
        console.log('propertyCodeTemp2:', propertyCodeTemp2.value);//roleType
        if (item[propertyCodeTemp2.value] == value) {
          tempValue = item[properType];
        }
      })

      console.log('tempValue', tempValue);
      listArray.forEach((item, index, array) => {
        if (item.propertyType === "list10") {
          item.value = tempValue;
        }
      })

      //初始list其他属性的值，根据carTempList的value，找着rout对着关系，然后赋值到addCarArr中
      console.log('addCarArr:', addCarArr);   //页面相关基本属性（非dic，list）的值
      let listName = 'field6';
      //从list跳转到增加主体的找着rout对着关系，
      let url = "/transaction/sub/fetchChannelRoute?relationFlag=4&entityCode=" + toEntityCode + "&entityType=" + toEntityType + "&otherEventCode=" + '002' + "&otherEntityCode=" + entityCode.value + "&otherEntityType=" + childCode.value;
      getRequest(url, (data) => {

        data.forEach(z => {
          addCarArr.value.forEach(x => {

            if (x.label === z.otherPropertyEnglish) {     //跳转目标主体的项目与映射参谋项目一致

              // carTempList.forEach(y => {

              console.log('z.propertyEnglish：', z.propertyEnglish);
              carTempList.forEach((item, index, array) => {
                console.log('carTempList里面properType:', properType);

                if (item[properType] == tempValue) {
                  x.value = item[z.propertyEnglish];
                }
              })


              // 如果 carTempList中的 listName（field5)与选择的值value相等的时候 if(y.listName === value)
              // 取得该carTempList记录里面的（跳转映射参数PropertyEnglish的定义，单位field3）的值，赋值到x.value中

              // x.value = '斤';



              // })


            }

            // for (let item in val.temp) {
            //   if (x.label === item && x.label === z.otherPropertyEnglish) {
            //     x.value = val.temp[item]
            //   }
            //
            // }

          })
        })
        //
        // console.log('tempListCode',tempListCode)
        // addCarArr.value.forEach(x => {
        //   // if (x.type === 'list10') {
        //   //   x.value = val.temp[tempListCode]
        //   // }
        //   if (x.type === propertyType0) {
        //     console.log("点击事件x.value",x.value)
        //     x.value = val.temp[tempListCode]
        //   }
        // })

      })







    }


    /**
     * 选择名称从而拿到值
     */
    function selectStoreName21(value) {
      console.log('value:', value);
      console.log('listArray:', listArray);
      console.log('carTempList21:', carTempList21);  //list对象的所有值
      console.log('开始addCarArr:', addCarArr);

      let properType = ''
      listArray.forEach((item, index, array) => {

        if (item.propertyType === "list20") {
          properType = item.propertyCode;
        }

      })

      properType = propertyCodeTemp1.value;
      console.log('properType:', properType);//roleType

      let tempValue = ''
      carTempList21.forEach((item, index, array) => {
        console.log('propertyCodeTemp2:', propertyCodeTemp2.value);//roleType
        if (item[propertyCodeTemp2.value] == value) {
          tempValue = item[properType];
        }
      })

      console.log('tempValue', tempValue);
      listArray.forEach((item, index, array) => {
        if (item.propertyType === "list20") {
          item.value = tempValue;
        }
      })

      //初始list其他属性的值，根据carTempList的value，找着rout对着关系，然后赋值到addCarArr中
      console.log('addCarArr:', addCarArr);   //页面相关基本属性（非dic，list）的值
      let listName = 'field6';
      //从list跳转到增加主体的找着rout对着关系，
      let url = "/transaction/sub/fetchChannelRoute?relationFlag=4&entityCode=" + toEntityCode21 + "&entityType=" + toEntityType21 + "&otherEventCode=" + '002' + "&otherEntityCode=" + entityCode.value + "&otherEntityType=" + childCode.value;
      getRequest(url, (data) => {

        data.forEach(z => {
          addCarArr.value.forEach(x => {

            if (x.label === z.otherPropertyEnglish) {     //跳转目标主体的项目与映射参谋项目一致

              // carTempList.forEach(y => {

              console.log('z.propertyEnglish：', z.propertyEnglish);
              carTempList21.forEach((item, index, array) => {
                console.log('carTempList里面properType:', properType);

                if (item[properType] == tempValue) {
                  x.value = item[z.propertyEnglish];
                }
              })


              // 如果 carTempList中的 listName（field5)与选择的值value相等的时候 if(y.listName === value)
              // 取得该carTempList记录里面的（跳转映射参数PropertyEnglish的定义，单位field3）的值，赋值到x.value中

              // x.value = '斤';



              // })


            }

            // for (let item in val.temp) {
            //   if (x.label === item && x.label === z.otherPropertyEnglish) {
            //     x.value = val.temp[item]
            //   }
            //
            // }

          })
        })
        //
        // console.log('tempListCode',tempListCode)
        // addCarArr.value.forEach(x => {
        //   // if (x.type === 'list10') {
        //   //   x.value = val.temp[tempListCode]
        //   // }
        //   if (x.type === propertyType0) {
        //     console.log("点击事件x.value",x.value)
        //     x.value = val.temp[tempListCode]
        //   }
        // })

      })







    }






    let brandList = ref(tempBrandList)
    function getBrandList(propertyCode) {
      console.log("propertyCode", propertyCode);

      let labelName = propertyCode
      console.log('getBrandList_propertyCode', propertyCode);
      const reqData = {
        "companyId": userData.companyId,
        "entityCode": entityCode.value,
        "entityType": childCode.value,
        "eventCode": operateEvent.value,
        "propertyCode": propertyCode
      }
      postRequest('channel/channel/getPropertyInterface', reqData, res => {
        if (res.status == "SUCCESS") {
          const tempArray = []
          let getListUrl = res.data.interfaceEnglish;
          let reqData = Object.assign({ "companyId": userData.companyId }, store.state.sphinx.selectedItemData[store.state.sphinx.selectedItemData.length - 1]);
          postRequest(getListUrl, reqData, res => {
            console.log("res", res);

            res.forEach((item, index, array) => {
              console.log("item", item);
              /******************************************/
              tempArray.push(item[labelName])
              // tempArray.push(item.relationCode)
              tempBrandList = tempArray
              console.log("tempBrandList=", tempBrandList);

            })
          })
        }
      })
    }

    function selectBrand(val) {
      brandFlag.value = true;
      const entityNo = val.split('.');
      // console.log(entityNo[0]);
      reqBrandData.value = {
        "entityCode": "201",
        "entityType": "00",
        "length": "999",
        "isRoot": "0",
        "chainHead": "0",
        "entityNo": entityNo[0]
      }
    }

    function filterBrandFn(val, update, abort) {
      if (val === '') {
        update(() => {
          brandList.value = tempBrandList
        })
        return
      }

      update(() => {
        const needle = val.toLowerCase()
        brandList.value = tempBrandList.filter(v => v.toLowerCase().indexOf(needle) > -1)
      })
    }

    function tickedBrandFn(tickedId) {
      console.log(tickedBrand)
      console.log(tickedId);
    }


    function tickedFn(tickedId) {
      // console.log(tickedId);
      console.log(ticked.value);
    }

    onMounted(() => {
      console.log('保存的链', ChainData);
      if (rote.query.childCode == "01113" || rote.query.childCode == "01120") {
        reqData.value = {
          "entityCode": "201",
          "entityType": "02",
          "length": "999",
          "isRoot": "0",
          "chainHead": "0",
          "entityNo": "71001000202111220000007"
        }
      } else {
        reqData.value = {
          "entityCode": "301",
          "entityType": "01",
          "length": "999",
          "isRoot": "0",
          "chainHead": "0",
          "entityNo": "71001000202111220000007"
        }
      }

      console.log("初始onMounted,rote.query.entityCode:", rote.query.entityCode);
      console.log("初始onMounted,rote.query.childCode:", rote.query.childCode);

      getFirstEntity();
      console.log("初始onMounted,entityCode", entityCode);
      entityCode.value = rote.query.entityCode;
      childCode.value = rote.query.childCode;
      console.log("初始onMounted,entityCode", entityCode);
      console.log("初始onMounted,childCode", childCode);
      //获取需要表单头信息，显示
      getAddClomn()
      getAdddataUrl()
      console.log("初始完成onMounted,entityCode", entityCode);
      console.log("初始完成onMounted,childCode", childCode);

    });

    function uploadOtherAccessoryFile(file) {
      let reader = new FileReader();
      reader.addEventListener("load", function () {
        api.post('/file/file/uploadPC', { file: reader.result }).then(res => {
          let inValue = addCarArr.value;
          inValue.forEach((item, index, array) => {
            if (item.label == imageControlItem) {
              if (item.value.length > 0) {
                item.value.push(res.data)
              } else {
                item.value = []
                item.value.push(res.data)
              }
            }
          })
          addCarArr.value = inValue
          console.log('213', addCarArr)
        })
      }, false);
      if (file) {
        reader.readAsDataURL(file[0]);
      }
    }

    let uploadFileStatus = ref(0)

    let preToAddImages = {}

    async function touchFileUpload(item) {
      imageControlItem = item;
    }
    async function uploadedFile(e, index) {
      let currentImageKey = imageControlItem
      addCarArr.value[index]['uploadFileStatus'] = 1
      let file = e[0]
      const formData = new FormData();
      formData.append('file', file);
      const url = process.env.api + '/servers/uploadImage';
      const axios = require('axios')
      try {
        const response = await axios.post(url, formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        });
        console.log('文件上传成功:', response.data.data);
        preToAddImages[currentImageKey] = response.data.data
        addCarArr.value[index]['uploadFileStatus'] = 2
      } catch (error) {
        console.log('文件上传失败')
        addCarArr.value[index]['uploadFileStatus'] = 3
      }
    }

    function removeImageFile() {

    }

    return {
      tickedBrandFn,
      selectBrand,
      getBrandList,
      brandList,
      selectStoreName,
      selectStoreName21,
      getSystemCode,
      firstEntityArr,
      searchDic,
      onSubmit,
      addCarArr,
      addDataUrl,
      entityCode,
      toEntityCode,
      toEntityCode21,
      onReset,
      QueryBarUrl,
      model,
      filterFn,
      setModel,
      change,
      touch,
      yeso,
      dicOptions,
      selections,
      dicArray,
      getNumber,
      fix,
      listArray,
      entity,
      mode,
      reqData,
      ticked,
      tickedFn,
      alert,
      carStoreNameList,
      carStoreNameList21,
      carTempList,
      carTempList21,
      propertyCodeTemp,
      propertyCodeTemp1,
      propertyCodeTemp2,
      filterBrandFn,
      childCode,
      toEntityType,
      toEntityType21,
      reqBrandData,
      brandFlag,
      tickedBrand,
      getBrandCode,
      uploadOtherAccessoryFile,
      touchFileUpload,
      uploadedFile,
      uploadFileStatus,
      imageControlItem
    };
  },
  data() {
    return {

    }
  },
  methods: {

  },
  mounted() {

    localStorage.setItem('lastPageName', 'add')
  }
});
</script>
<style scoped></style>
